package sunsun.xiaoli.jiarebang.utils;

import android.os.Handler;
import android.os.Message;
import com.google.gson.Gson;
import com.itboye.pondteam.app.MyApplication;
import sunsun.xiaoli.jiarebang.app.App;
import sunsun.xiaoli.jiarebang.beans.SearchDeviceInfo;
import sunsun.xiaoli.jiarebang.utils.wifiutil.AqSmartConfig;

import java.io.IOException;
import java.net.*;

/**
 */
public class AqDeviceFind {
    public DatagramSocket mUdpSocket = null;
    public int mUdpPort = 0;
    public Thread mThread = null;
    private boolean mThreadIsRun = false;
    public Handler mHandler;
    private MulticastSocket sender;
    private SearchDeviceInfo searchDeviceInfo;
    String req = "{\"req\":\"device_info\"}";
    int port = 0;
    private Thread myThread = null;
    String TAG = "Smart_config";

    public AqDeviceFind(Handler handler) {
        mHandler = handler;
    }

    public AqDeviceFind() {
    }

    public boolean isRun() {
        if (mThread == null) {
            return false;
        }
        return mThreadIsRun;
    }

    public boolean isRunMyThread() {
        if (mThread == null) {
            return false;
        }
        return mThreadIsRun;
    }

    /**
     * 开始查找设备
     *
     * @param port 监听端口，默认15151
     * @return 已经运行或者运行失败返回false，成功返回true
     */
    public boolean start(int port) {
        this.port = port;
//        //搜索摄像头
//        if (!BuildConfig.APP_TYPE.equals("森森新零售")) {
//            chirdDeviceSearch();
//        }
        //其他设备
        new udpBroadCast(req, port).start();
        return true;
    }

    DatagramPacket dj;
    Gson gson = new Gson();

    /* 发送udp多播 */
    private class udpBroadCast extends Thread {
        InetAddress group = null;
        byte[] data = new byte[1024];
        int port = 0;

        public udpBroadCast(String dataString, int port) {
            data = dataString.getBytes();
            this.port = port;
        }

        @Override
        public void run() {
            // 变量
            // 判断是否处于局域网
            String gwip = new AqSmartConfig(MyApplication.getInstance()).getGateway();
            if (gwip == null) {
                return;
            }
            String[] gwips = gwip.split(".");
            // 接收循环
            while (!Thread.currentThread().isInterrupted()) {
                DatagramPacket dpr = null;
                // 创建UDP
                if (App.getInstance().isStartSearch) {
                    try {
                        group = InetAddress.getByName("255.255.255.255");
                        dpr = new DatagramPacket(data, data.length, group, port);
                        mUdpSocket = new DatagramSocket();
                        mUdpSocket.setBroadcast(true);
                        mUdpSocket.setSoTimeout(2000);
                        try {
                            mUdpSocket.send(dpr);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } catch (SocketException e) {
                        if (mThread != null) {
                            mThread.interrupt();
                        }
                    } catch (UnknownHostException e) {
                        if (mThread != null) {
                            mThread.interrupt();
                        }
                    }
                    try {
                        byte[] bufferIn = new byte[256];
                        DatagramPacket dpIn = new DatagramPacket(bufferIn, bufferIn.length);
                        mUdpSocket.receive(dpIn);
                        String packData = new String(bufferIn, 0, bufferIn.length, "gb2312");
                        packData = packData.replaceAll("\u0000", "");
                        searchDeviceInfo = gson.fromJson(packData, SearchDeviceInfo.class);
                        sendMessage(searchDeviceInfo);
                        mUdpSocket.close();
                        if (mThread != null) {
                            mThread.interrupt();
                        }
                        Thread.sleep(1000);
//                        LogUtils.v(TAG, "接收到广播 转码后：" + packData);
                    } catch (Exception e) {
                        e.printStackTrace();
                        mUdpSocket.close();
                        if (mThread != null) {
                            mThread.interrupt();
                        }
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e1) {
                            e1.printStackTrace();
                        }
//                        LogUtils.v(TAG, "广播异常==" + e.getMessage());
                    }
                } else {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }
    }

    private void chirdDeviceSearch() {
    }


    Handler mTimeHandler;
    Runnable mTimeRunnable;


    private void sendMessage(SearchDeviceInfo searchDeviceInfo) {
        Message message = new Message();
        message.obj = searchDeviceInfo;
        if (mHandler != null) {
            mHandler.sendMessage(message);
        }
    }

    public boolean stop() {
        if (isRun()) {
            mThread.interrupt();
            try {
                mThread.join();
            } catch (InterruptedException e) {
            }
            return true;
        }
        return false;
    }

//    public boolean stopSearch() {
//        if (handler != null) {
//            handler.removeCallbacks(runnable);
//        }
//        return false;
//    }
}
